package com.cskaoyan.controller;

import com.cskaoyan.bean.*;

import com.cskaoyan.service.AdminCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author pengyehua
 * @date 2020/12/6 16:23
 */

/**
 * 商品管理模块的商品类目
 */
@RestController
@RequestMapping("admin/category")
public class AdminCategoryController {

    @Autowired
    AdminCategoryService adminCategoryService;

    /**
     *查询一级类目
     * @return
     */
    @GetMapping("l1")
    public BaseRespVo l1(){
        List<CategoryBO> categoryBOList = adminCategoryService.queryIdAndName();
        return BaseRespVo.ok(categoryBOList);

    }

    /**
     * 查询商品类目信息
     * @return
     */
    @GetMapping("list")
    public BaseRespVo list(){
        List<CategoryL1> categoryL1List = adminCategoryService.queryCategory();
        return BaseRespVo.ok(categoryL1List);
    }

    /**
     * 插入商品类目
     * @param category
     * @return
     */
    @PostMapping("create")
    public BaseRespVo create(@RequestBody Category category){

         Category categoryVo = adminCategoryService.insertCategory(category);
         return BaseRespVo.ok(categoryVo);
    }

    /**
     * 修改商品类目
     * @param category
     * @return
     */
    @PostMapping("update")
    public BaseRespVo update(@RequestBody Category category){
        adminCategoryService.updateCategory(category);
        return BaseRespVo.ok();
    }

    /**
     * 删除商品类目
     * @param category
     * @return
     */
    @PostMapping("delete")
    public BaseRespVo deleteCategory(@RequestBody Category category){
        //如果是删除一级类目，先判断一级类目下是否还有二级类目
        if(category.getLevel().equals("L1")){
            int count = adminCategoryService.queryL2Count(category);
            if (count > 0){
                return BaseRespVo.fail("该类目下还有二级类目没有被删除干净");
            }
        }
        //如果是删除二级类目，先判断二级类目下是否还有商品
        if(category.getLevel().equals("L2")){
            int goodsCount = adminCategoryService.queryGoodsCount(category);
            if(goodsCount > 0){
                return BaseRespVo.fail("该类目下还有商品没有被删除干净");
            }
        }
            adminCategoryService.deleteCategory(category);
            return BaseRespVo.ok();
    }


}
